import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

import 'ant-design-vue/dist/antd.css'

Vue.use(Vuex)

Vue.config.productionTip = false

export default new Vuex.Store({
  state: {
    // 所有的任务列表
    list: [],
    // 文本框的内容
    inputValue: '',
    viewKey: 'all'
  },
  getters: {
    // 统计未完成的任务的条数
    upDoneLength (state) {
      return state.list.filter(x => x.done === false).length
    },
    infoList (state) {
      if (state.viewKey === 'all') return state.list
      else if (state.viewKey === 'unDone') return state.list.filter(x => !x.done)
      else if (state.viewKey === 'done') return state.list.filter(x => x.done)
      return state.list
    }
  },
  mutations: {
    initList (state, list) {
      state.list = list
    },
    // 为 store 中的inpuValue 赋值
    setInputValue (state, val) {
      state.inputValue = val
    },
    // 添加列表项目
    addItem (state) {
      // 下一个Id
      const nextId = state.list.length
      const obj = {
        id: nextId,
        info: state.inputValue.trim(0),
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    removeItem (state, id) {
      // 根据Id查找对影响的索引
      const i = state.list.findIndex(x => x.id === id)
      // 根据索引，删除对应的元素
      if (i !== -1) state.list.splice(i, 1)
    },
    // 修改列表项的选中状态
    changeStatus (state, param) {
      const i = state.list.findIndex(x => x.id === param.id)
      if (i !== -1) state.list[i].done = param.status
    },
    // 清楚已完成的任务
    cleanDone (state) {
      state.list = state.list.filter(x => x.done === false)
    },
    changeViewKey (state, key) {
      state.viewKey = key
    }
  },
  actions: {
    getList (context) {
      axios.get('/list.json').then(({ data }) => {
        console.log(data)
        context.commit('initList', data)
      })
    }
  },
  modules: {
  }
})
